import websocket
import time
import urllib.request
import urllib.parse
import json
import http.client



def openConnection (clientID, clientSecret):
  ws=websocket.create_connection("wss://client.pushover.net/push");
  ws.send("login:"+clientID+":"+clientSecret+"\n")
  return ws


def deleteAllMessages(clientID, clientSecret):
  response = urllib.request.urlopen("https://api.pushover.net/1/messages.json?secret="+clientSecret+"&device_id="+clientID)
  waitingMessages = response.read()
  
  jsonMessages=json.loads(str(waitingMessages, encoding='UTF-8'))
  #Strip out the uneeded headers
  jsonMessages=jsonMessages["messages"]
  numberOfMessages=len(jsonMessages)
  #If messages are present just delete them
  if (numberOfMessages>0):
    highestMessageID=jsonMessages[numberOfMessages-1]["id"]
    values = {'secret':clientSecret,
              'message':highestMessageID}
    data = urllib.parse.urlencode(values);
    data = data.encode('utf-8')
    req = urllib.request.urlopen("https://api.pushover.net/1/devices/"+clientID+"/update_highest_message.json", data)
    
  
def downloadMessages(clientID, clientSecret):
  response = urllib.request.urlopen("https://api.pushover.net/1/messages.json?secret="+clientSecret+"&device_id="+clientID)
  waitingMessages = response.read()
  
  jsonMessages=json.loads(str(waitingMessages, encoding='UTF-8'))
  #Strip out the uneeded headers
  jsonMessages=jsonMessages["messages"]
  numberOfMessages=len(jsonMessages)
  
  if (numberOfMessages>0):
    highestMessageID=jsonMessages[numberOfMessages-1]["id"]
    # Now tell Pushover that we dealt with all pending messages
    values = {'secret':clientSecret,
              'message':highestMessageID}
    data = urllib.parse.urlencode(values);
    data = data.encode('utf-8')
    req = urllib.request.urlopen("https://api.pushover.net/1/devices/"+clientID+"/update_highest_message.json", data)
    
  return jsonMessages
   
def sendMessage(token, recipient, title, message, sound="pushover", priority=0,device=""):
  conn = http.client.HTTPSConnection("api.pushover.net:443")
  print (device)
  conn.request("POST", "/1/messages.json",
               urllib.parse.urlencode({
                 "token": token,
                 "user": recipient,
                 "device":device,
                 "message": message,
                 "title": title,
                 "sound": sound,
                 "priority":priority,
                 }), { "Content-type": "application/x-www-form-urlencoded" })
  conn.getresponse()
 